#!/bin/bash

### BEGIN INIT INFO
# Provides:          firstrun
# Required-Start:    $all
# Required-Stop:
# Should-Start:      
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Script to run when first starting
# Description:       Something needs to be done when  is
#                    starting at first time.
#                    regenerate ssh host key
### END INIT INFO

N=/etc/init.d/firstrun

set -e

do_expand_rootfs(){
  if grep -qs "sda2\s*/\s*" /etc/fstab; then
    device="/dev/sda"
    rootpart="/dev/sda2"
  elif grep -qs "mmcblk0p2\s*/\s*" /etc/fstab; then
    device="/dev/mmcblk0"
    rootpart="/dev/mmcblk0p2"
  else
    device="/dev/"$(lsblk -idn -o NAME | grep mmc)
    rootpart=$(mount | sed -n -e 's/ on \/ .*//p')
  fi
  
  PARTITIONS=$(($(fdisk -l $device | grep $device | wc -l)-1))
  
  echo Editing the partition table... 
  ( (echo d; echo $PARTITIONS; echo n; echo p; echo ; echo ; echo ; echo w; ) | 
    fdisk $device )>/dev/null
  sync
  
  echo Probing the partition table... 
  partx -u ${device} || return $?
  
  echo Resizing the partition... 
  resize2fs ${rootpart} || return $?
  sync
}

regenerate_ssh_keys(){
  echo "SSH keys recreation. One moment please"
  rm -f /etc/ssh/ssh_host*
  dpkg-reconfigure openssh-server
  rm /etc/init/ssh.override
  service ssh start
}

on_background(){
  sleep 10
  regenerate_ssh_keys
  echo "Removing firstrun script"
  update-rc.d -f firstrun remove >/dev/null 2>&1
  sync
}

case "$1" in
  start)
    set +e
    echo "Expanding rootfs..." 

    if do_expand_rootfs ;
    then
      echo "Expanding partition success" 
    else
      echo "Expanding rootfs has failed, see log files. Error code: $?" 
    fi

    on_background &
    
    if `rm /etc/init/lightdm.override 2>/dev/null`
      then
      service lightdm start
    fi
  ;;
  
  *)
    echo "Usage: $N {start}" >&2
    exit 1
  ;;
esac
  
exit 0
